<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="80%"
    custom-class="custom-dialog"
    @close="onClose"
  >
    <!-- 模板说明与下载 -->
    <div class="excel-tpl">
      <span class="tpl-text">上传前请先按 Excel 模板格式编辑内容</span>
      <a :href="templateUrl" class="downlink" download>
        <img :src="excelIcon" alt="Excel Icon" style="width:16px;height:16px" class="excel-icon" />
        <span class="download-text">下载 Excel 模板</span>
      </a>
    </div>

    <!-- 拖拽上传区域，只有在未上传文件时显示 -->
    <el-upload
      v-if="!isFileUploaded"
      class="upload-area"
      drag
      action=""
      :auto-upload="false"
      :limit="1"
      :file-list="fileList"
      :before-remove="handleBeforeRemove"
      :on-change="handleFileChange"
      accept=".xlsx,.xls"
    >
      <icon icon="ri-upload-2-fill" size="40px" class="upload-icon" />
      <div class="el-upload__text">
        <p class="upload-text">将 Excel 文件拖拽到此处，或点击上传</p>
      </div>
      <template #tip>
        <div class="el-upload__tip">支持 xls, xlsx 格式，建议文件小于 5MB</div>
      </template>
    </el-upload>

    <!-- 表格预览，只有在文件上传后显示 -->
    <div v-if="isFileUploaded" class="table-preview mt-4">
      <el-table
        :data="tableData"
        border
        stripe
        height="400px"
        class="custom-table"
      >
        <el-table-column
          v-for="(col, idx) in props.columns"
          :key="idx"
          :prop="col.dataIndex"
          :label="col.name"
          show-overflow-tooltip
          align="center"
          header-align="center"
          class-name="custom-column"
        >
          <template #default="{ row }">
            <div class="cell-wrapper">
              <!-- 开关类型 -->
              <el-switch
                v-if="col.formType === 'switch'"
                v-model="row[col.dataIndex]"
                :active-value="1"
                :inactive-value="0"
                active-color="#28a745"
                inactive-color="#dc3545"
                class="custom-switch"
              />
              <!-- 输入框类型 -->
              <el-input
                v-else
                v-model="row[col.dataIndex]"
                size="small"
                clearable
                placeholder="请输入内容"
                class="custom-input"
                :maxlength="col.maxLength || 50"
                @input="handleInput(row, col)"
              />
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="{ $index }">
            <el-button
              type="danger"
              size="small"
              class="delete-btn"
              @click="removeRow($index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 导入说明 -->
    <el-card
      shadow="never"
      class="instructions"
      v-if="!isFileUploaded"
      style="margin-top: 20px"
    >
      <p class="instruction-title">导入规则：</p>
      <ol class="instruction-list">
        <li>请下载模板并按格式填写待导入信息。</li>
        <li>支持以下字段：{{ columnLabels.join(", ") }}</li>
        <li>建议每次上传数据不超过 {{maxLimit}} 行。</li>
        <li>文件大小建议小于 5MB，避免导入失败。</li>
      </ol>
    </el-card>

    <!-- 操作按钮 -->
    <template #footer>
      <el-button class="cancel-btn" @click="visible = false">取消</el-button>
      <el-button
        type="primary"
        class="submit-btn"
        :disabled="!tableData.length"
        @click="submitData"
        >提交</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineExpose, defineProps, defineEmits, computed } from "vue";
import * as XLSX from "xlsx";
import { ElMessage } from "element-plus";
import excelIcon from "@/assets/svg/excel.svg";

const props = defineProps({
  columns: {
    type: Array,
    required: true,
  },
  templateUrl: {
    type: String,
    default: "",
  },
  maxLimit: {
    type: Number,
    default: 100,
  },
  title:{
    type:String,
    default:'批量导入'
  }
});

const emit = defineEmits(["submit"]);

const visible = ref(false);
const tableData = ref([]);
const fileList = ref([]);
const isFileUploaded = ref(false);

const columnLabels = computed(() => props.columns.map((col) => col.name));

// 打开弹窗
const open = () => {
  visible.value = true;
};
defineExpose({ open });

// Excel 上传变化处理
function handleFileChange(uploadFile) {
  const file = uploadFile.raw;
  if (!file) return;

  fileList.value = [uploadFile];

  const reader = new FileReader();
  reader.onload = (evt) => {
    const data = new Uint8Array(evt.target.result);
    const workbook = XLSX.read(data, { type: "array" });
    const sheet = workbook.Sheets[workbook.SheetNames[0]];
    const jsonData = XLSX.utils.sheet_to_json(sheet);

    // 校验行数是否超出限制
    if (jsonData.length > props.maxLimit) {
      ElMessage.error(
        `上传数据超过最大限制（${props.maxLimit} 行），请重新上传`
      );
      fileList.value = [];
      tableData.value = [];
      isFileUploaded.value = false;
      return;
    }

    // 映射字段
    const mapped = jsonData.map((row) => {
      const item = {};
      props.columns.forEach((col) => {
        item[col.dataIndex] = row[col.name] ?? "";
      });
      return item;
    });
    tableData.value = mapped;
    isFileUploaded.value = true;
  };
  reader.readAsArrayBuffer(file);
}

// 删除上传文件阻止操作
function handleBeforeRemove() {
  ElMessage.warning("不允许删除上传文件，请刷新页面重新上传");
  return false;
}

// 移除某一行数据
function removeRow(index) {
  tableData.value.splice(index, 1);
  if (!tableData.value.length) {
    isFileUploaded.value = false;
  }
}

// 提交数据
function submitData() {
  emit("submit", tableData.value);
  visible.value = false;
  tableData.value = [];
  fileList.value = [];
  isFileUploaded.value = false;
}

// 弹窗关闭时清空
function onClose() {
  tableData.value = [];
  fileList.value = [];
  isFileUploaded.value = false;
}

// 输入框输入时处理
function handleInput(row, col) {
  // 可根据需要添加输入校验逻辑
}
</script>

<style scoped lang="less">
.custom-dialog {
  border-radius: 8px;
  overflow: hidden;

  .el-dialog__header {
    padding: 15px 20px;
    background-color: #f8f9fa;
  }

  .el-dialog__title {
    font-size: 18px;
    font-weight: 500;
    color: #333;
  }

  .el-dialog__body {
    padding: 20px;
  }
}

.excel-tpl {
  padding: 12px;
  background: #e9f0ff;
  color: #2c3e50;
  margin-bottom: 20px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .tpl-text {
    font-size: 14px;
  }

  .downlink {
    margin-left: 10px;
    color: #409eff;
    display: flex;
    align-items: center;
    text-decoration: none;
    transition: color 0.3s;

    &:hover {
      color: #66b0ff;
    }
  }

  .excel-icon {
    width: 18px;
    height: 18px;
    margin: 0 6px;
  }

  .download-text {
    font-size: 14px;
  }
}

.upload-area {
  padding: 30px 0;
  text-align: center;
  margin-bottom: 20px;
  background: #ffffff;
  border-radius: 6px;
  transition: border-color 0.3s;

  &:hover {
    border-color: #409eff;
  }

  .upload-icon {
    color: #409eff;
  }

  .el-upload__text {
    margin-top: 10px;
  }

  .upload-text {
    font-size: 14px;
    color: #606266;
  }

  .el-upload__tip {
    font-size: 12px;
    color: #909399;
  }
}

.table-preview {
  margin-top: 20px;
  border: 1px solid #dee2e6;
  border-radius: 6px;
  overflow: hidden;
}

.custom-table {
  .el-table__header {
    background-color: #f8f9fa;
    font-weight: 500;
  }

  .el-table__row {
    transition: background-color 0.3s;

    &:hover {
      background-color: #f1f3f5 !important;
    }
  }
}

::v-deep .custom-column.el-table__cell {
  padding: 0 !important;
}

.cell-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 36px;
}

.custom-input {
  width: 100%; // 填充单元格宽度
  box-sizing: border-box; // 确保内边距和边框不影响宽度

    .el-input__wrapper{
        padding: 0;
    }
  :deep(.el-input__inner) {
    border-radius: 4px;
    padding: 0 8px;
    height: 28px;
    font-size: 12px;
    transition: all 0.3s;

    &:hover {
      border-color: #c0c4cc;
    }

    &:focus {
      border-color: #409eff;
    }
  }
}

.custom-switch {
  :deep(.el-switch__core) {
    border-radius: 14px;
    width: 44px !important;
    height: 22px;

    .el-switch__action {
      width: 18px;
      height: 18px;
    }
  }
}

.delete-btn {
  padding: 6px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;

  &:hover {
    background-color: #c82333;
  }
}

.instructions {
  background-color: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  border-left: 4px solid #17a2b8;

  .instruction-title {
    font-size: 16px;
    font-weight: 600;
    color: #17a2b8;
    margin-bottom: 10px;
  }

  .instruction-list {
    padding-left: 18px;
    list-style: decimal;
    color: #495057;
    font-size: 14px;

    li {
      margin-bottom: 8px;
    }
  }
}

.cancel-btn {
  padding: 8px 20px;
  border-radius: 4px;
  background-color: #ffffff;
  border: 1px solid #dcdcdc;
  transition: all 0.3s;

  &:hover {
    background-color: #f1f1f1;
    border-color: #c0c4cc;
  }
}

.submit-btn {
  padding: 8px 20px;
  border-radius: 4px;
  background-color: #409eff;
  transition: all 0.3s;

  &:hover {
    background-color: #66b0ff;
  }

  &:disabled {
    background-color: #dcdcdc;
    cursor: not-allowed;
  }
}
</style>